import os
import time
import json
import execjs
import threading
import requests
import webbrowser
from flask_cors import *
from time import sleep
from flask import Flask, request
from random import randint


def exce_node_js_obj_data(top, right, level, t_nums):
    os.environ["NODE_PATH"] = os.getcwd()
    nodejs = execjs.compile("""
        function getMapData(top, right, level) {
            var leftTop = top.split(',')
            var RightBottom = right.split(',')
            var TileLnglatTransformBaidu = require('ConfigPoint').TileLnglatTransformBaidu;
            let mapData = {}
            t = TileLnglatTransformBaidu.lnglatToTile(
                leftTop[0], leftTop[1], level)
            r = TileLnglatTransformBaidu.lnglatToTile(
                RightBottom[0], RightBottom[1], level)
            mapData.x = [t.tileX, r.tileX]
            mapData.y = [r.tileY, t.tileY]
            return mapData;
        }
    """)
    get_tiles(nodejs.call("getMapData", top, right, level), level, t_nums)


def thread_downlaod(arr):
    for url in list(arr):
        print(url)
        save_pictures_via_url(url)


def get_tiles(obj, z, t_nums):
    print(obj)
    xidx = obj['x']
    yidx = obj['y']
    arr_list_url = []

    for y in range(yidx[0], yidx[1]+1):
        for x in range(xidx[0], xidx[1]+1):
            try:
                if not os.path.isdir(path+'/'+str(z)+'/'+str(x)+'/'):
                    os.makedirs(path+'/'+str(z)+'/'+str(x)+'/')
            except:
                pass

    for y in range(yidx[0], yidx[1]+1):
        for x in range(xidx[0], xidx[1]+1):
            url = "http://maponline{i}.bdimg.com/tile/?qt=vtile&x={x}&y={y}&z={z}&styles=pl" \
                "&scaler=1&udt={t}&from=jsapi2_0".format(
                    i=randint(0, 3), x=x, y=y, z=z, t=time.strftime("%Y%m%d", time.localtime()))
            arr_list_url.append(url)

    arr_list_url = list_split(arr_list_url, 55 - t_nums)
    for url_list in arr_list_url:
        try:
            t_d = threading.Thread(
                target=thread_downlaod, args=(url_list,))
            t_d.start()
        except:
            print('error')


def list_split(items, n):
    return [items[i:i+n] for i in range(0, len(items), n)]


def openFileName():
    start_directory = os.getcwd()+"\\map\\"
    os.startfile(start_directory)


def save(res, x, y, z):
    sname = path+'/'+z+'/'+x+'/'+"/{y}.png".format(y=y)
    with open(sname, 'ab') as pngf:
        for chunk in res.iter_content(chunk_size=1024):
            if chunk:
                pngf.write(chunk)
                pngf.flush()


def save_pictures_via_url(url):
    arr = url.split("&")
    save(requests.get(url),
         arr[1].replace("x=", ""),
         arr[2].replace("y=", ""),
         arr[3].replace("z=", ""))


app = Flask(__name__)
CORS(app, supports_credentials=True)
path = ""


@app.route('/api/download', methods=['POST'])
def download():
    data = json.loads(request.get_data(as_text=True))
    try:
        top = data['top']
        right = data['right']
        zoom_level = data['zoomLevel']
        file_name = data['fileName']
        t_nums = data['nums']
        global path
        path = os.getcwd()+"\\map\\"+file_name+"\\"
        arr_lev = zoom_level.split(",")
        for lev in arr_lev:
            if not os.path.isdir(path+'/'+lev):
                os.makedirs(path+'/'+lev)
            t_d = threading.Thread(
                target=exce_node_js_obj_data, args=(top, right, lev, t_nums))
            t_d.start()

        return {'code': 200, 'msg': '执行成功'}
    except:
        return {'code': 100, 'msg': '后台服务错误'}


@app.route('/api/openFile', methods=['GET'])
def openFile():
    openFileName()
    return {'code': 200, 'msg': '打开成功'}


@app.route('/api/getState', methods=['GET'])
def getState():
    if(len(threading.enumerate()) == 2):
        return {'code': 200, 'msg': '下载完成'}
    else:
        return {'code': 201, 'msg': '下载中请稍后!'}


@app.route('/api/stop', methods=['GET'])
def stop():
    os.system('cd ConfigPoint/nginx&&nginx -s stop')
    sleep(1)
    func = request.environ.get('werkzeug.server.shutdown')
    if func is None:
        raise RuntimeError('Not running with the Werkzeug Server')
    func()
    return {'code': 200, 'msg': '关闭成功'}

# def ing():
#     index = ["/", "─", "\\", ]
#     while bool(b_init):
#         for i in range(len(index)):
#             print("\r"+index[i], end="")
#             sleep(0.2)


if __name__ == "__main__":
    # b_init = True
    try:
        # print("Nginx服务正在启动")
        # sleep(1)
        # os.system('cd ConfigPoint/nginx&&start nginx')
        # print("Nginx服务启动成功")
        # print("服务正在启动")
        # t_d = threading.Thread(target=ing, args=())
        # t_d.start()
        # sleep(3)
        # b_init = False
        # webbrowser.open("http://localhost")
        # app.run(port=666)
        os.system('cd ConfigPoint/nginx&&start nginx')
        sleep(1)
        webbrowser.open("http://localhost:88")
        app.run(port=666)
    except:
        print('服务启动失败')
